<template>
  <div class="search-container">
    <!-- 搜索栏 -->
    <form action="/">
      <van-search
        v-model="searchText"
        placeholder="请输入搜索关键词"
        show-action
        @search="onSearch(searchText)"
        @cancel="$router.back()"
        @focus="isResultShow = false"
      />
    </form>
    <!-- 搜索结果 -->
    <search-result
      v-if="isResultShow"
      :search-text="searchText"></search-result>
    <!-- 联想建议 -->
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
      ></search-suggestion>
    <!-- 历史记录 -->
    <search-history
      v-else
      :search-histories="searchHistories"
      @search="onSearch"
      @update-histories="searchHistories = $event"></search-history>

  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchResult from './components/search-result.vue'
import SearchSuggestion from './components/search-suggestion'
import { setItem, getItem } from '@/utils/storage'
// import { getSearchHistories } from '@/api/search'
import { mapState } from 'vuex'
export default {
  name: 'SearchIndex',
  components: {
    SearchSuggestion,
    SearchHistory,
    SearchResult
  },

  props: {},

  data () {
    return {
      // 搜索输入框的内容
      searchText: '',
      // 控制搜索结果的显示状态
      isResultShow: false,
      // 搜索历史数据
      searchHistories: []
    }
  },

  computed: {
    ...mapState(['user'])
  },

  watch: {
    // 监视搜索历史记录的变化， 存储到本地存储
    searchHistories () {
      setItem('search-histories', this.searchHistories)
    }
  },

  created () {
    this.loadSearchHistories()
  },

  mounted () {},

  methods: {
    onSearch (searchText) {
      // 把输入框设置为你要搜索的文本
      this.searchText = searchText
      // 删除重复的搜索记录
      const index = this.searchHistories.indexOf(searchText)
      if (index !== -1) {
        // 把重复项删除
        this.searchHistories.splice(index, 1)
      }
      // 把最新的搜索记录放到顶部
      this.searchHistories.unshift(searchText)

      // 如果用户已经登录，就把搜索历史纪录存储到线上
      // 只要我们调用获取搜索结果的数据接口，后端会给我们自动存储用户的搜索历史记录
      // 如果没有登录，则把历史记录存储到本地
      // setItem('search-histories', this.searchHistories)

      // 展示搜索结果
      this.isResultShow = true
    },
    async loadSearchHistories () {
      // 因为后端只存储四条 历史记录
      // 所以我们合并本地存储和后端的历史记录

      const searchHistories = getItem('search-histories') || []
      // // 如果用户已经登录
      // if (this.user) {
      //   const { data } = await getSearchHistories()
      //   // 合并
      //   searchHistories = [...new Set([...searchHistories, ...data.data.keywords])]
      // }
      this.searchHistories = searchHistories
    }
  }
}

</script>
<style lang='less' scoped>
</style>
